import { _decorator, Component, Node } from 'cc';
import { CCComFun } from '../../util/CCComFun';
import { CCGlobal, VideoCall } from '../../util/CCGlobal';
import { gui } from '../../../gui/GUI';
import { AdsBase } from '../../AdsBase';
import { GameStatistics } from '../../statistics/GameStatistics';
import engine from '../../../Engine';
import { RecorderBase } from '../../RecorderBase';
const { ccclass, property } = _decorator;

@ccclass('TTAdsFunc')
export class TTAdsFunc extends AdsBase {
    private videoAd: video = null;


    public init(): void {
        let videoId = CCGlobal.Config.videoId;
        if (videoId) {
            this.videoAd = new video(videoId);
            this.videoAd.create();
        }
    }


    public loadVideoAd(opt: VideoCall): void {
        if (this.videoAd.videoShowing) {
            return CCComFun.CCLog("视频展示中,本次视频按钮点击无效");
        }
        if (!this.videoAd) {
            this.showToast();
            engine.StatMar.rewardVideo();
            return opt.errCallback && opt.errCallback();
        }
        this.videoAd.adCall = opt;
        this.videoAd.show();
    }

    public toSidebar(opt: VideoCall) {
        if (!CCGlobal.API.navigateToScene) {
            gui.showTips("暂不支持跳转侧边栏")
            return;
        }
        CCGlobal.API.navigateToScene({
            scene: 'sidebar',
            success: () => {
                opt.suCallback && opt.suCallback();
            },
            fail: () => {
                opt.failCallback && opt.failCallback();
            }
        })
    }

    /**添加桌面 */
    public addShortcut(opt: VideoCall) {
        CCGlobal.API.addShortcut({
            success: () => {
                opt && opt.suCallback && opt.suCallback();
            },
            fail: (err) => {
                console.log("添加桌面失败", err);
                opt && opt.failCallback && opt.failCallback();
            }
        })
    }


    public shareAppMessage(opt: VideoCall) {
        CCGlobal.API.shareAppMessage({
            success: () => {
                opt && opt.suCallback && opt.suCallback();
            },
            fail: () => {
                opt && opt.failCallback && opt.failCallback();
            }
        })
    }
}

class video extends AdsBase {
    constructor(id) {
        super()
        this.id = id;
    }

    public create() {
        this.ad = CCGlobal.API.createRewardedVideoAd({
            adUnitId: this.id
        })

        if (this.ad) {
            this.ad.onError(this._onError.bind(this));
            this.ad.onClose(this._onClose.bind(this));
        }
        CCComFun.CCLog("广告创建完毕")
    }

    public show() {
        if (!this.ad) {
            this.showToast();
            this.adCall && this.adCall.errCallback && this.adCall.errCallback();
            return;
        }

        this.videoShowing = true;
        this.videoShowing = true;
        let showPro = this.ad.show();
        showPro.then(() => {
            CCComFun.CCLog("[video] 视频广告展示成功");
        }).catch((err) => {
            CCComFun.CCLog("[video] 视频广告展示失败", err);
        })
    }

    private _onError(err) {
        CCComFun.CCLog("[video] 触发视频错误监听", err);
        this.videoShowing = false;
        this.showToast();
        this.adCall && this.adCall.errCallback && this.adCall.errCallback();
    }

    private _onClose(res) {
        this.videoShowing = false;
        if (res && res.isEnded || res === undefined) {
            this.adCall && this.adCall.suCallback && this.adCall.suCallback();
        } else {
            this.adCall && this.adCall.failCallback && this.adCall.failCallback();
        }
    }

    public destroy() {
        if (this.id) {
            this.ad.offError();
            this.ad.offClose();
            this.ad.destroy();
            this.ad = null;
            this.videoShowing = false;
        }
    }

}


export class TTRecorder extends RecorderBase {

    private _videoPath: any = null;

    public init() {
        if (engine.cc_debug) { return };
        this.recorder = CCGlobal.API.getGameRecorderManager();
        this.recorder.onStop((res) => {
            this._onStop(res);
        })
        console.log("初始化", JSON.stringify(this.recorder))
    }

    /**录制开始 */
    public recorderStart() {
        if (engine.cc_debug) { return };
        this.recorder.start()
    }

    /**停止录制并保存录像 */
    public recorderStop() {
        if (engine.cc_debug) { return };
        this.recorder.stop();
    }

    /**发布录像 */
    public publishVideo(opt: VideoCall) {
        if (engine.cc_debug) { return };

        CCGlobal.API.shareAppMessage({
            channel: "video",
            extra: { videoPath: this._videoPath },
            success() {
                gui.showTips("分享成功!");
                opt && opt.suCallback && opt.suCallback();
            },
            fail(err) {
                console.log("录屏失败", JSON.stringify(err));
                let title = "分享失败!";
                if (err && err.errNo && err.errNo === 21105) title = "录制时间过短";
                gui.showTips(title);
                opt && opt.failCallback && opt.failCallback();
            },
        })
    }


    private _onStop(res) {
        if (res && res.videoPath) {
            this._videoPath = res.videoPath;
        }
    }

}